<?php
namespace app\admin\controller;
use \think\Db;
use app\admin\service\MemberService;
use think;
use think\Cache;
use think\Loader;
use think\Session;
//个人会员处理
/**
 * Class Member 个人会员管理控制器
 * @package app\admin\controller
 */
class Member extends Admin
{       
    //个人会员列表
    public function index()
    {
        $param = $this->request->param();
        $memberService =new MemberService();
        $member = $memberService->index($param);
        $this->assign("member", $member);
        $this->assign("filter", $param);//设置过滤条件
        $this->setNav('会员列表');
        return $this->fetch();
    }
    public function checkMobile($mobile){
        $member = model('member');
        $field ='id,user_status,real_name,user_name';
        $result = $member->where('mobile', $mobile)->field($field)->find();
        if($result){
            return json(['code'=>1,'msg'=>'已经存在！','data'=>$result]);
        }else {
            return json(['code'=>1,'msg'=>'此号码不存在！','data'=>null]);
        }
    }
    //会员审核
    public function auditIndex()
    {
        $param = $this->request->param();
        $memberService =new MemberService();
        $member = $memberService->auditIndex($param);
        $this->assign("member", $member);
        $this->assign("filter", $param);//设置过滤条件
        $this->setNav('会员列表');
        return $this->fetch();
    }
    //会员审核界面
    public function auditPanel($id)
    {
        $member = model('member');
        $join = [
            ['__MEMBER_DETAIL__ member_detail','a.id = member_detail.mid'],
        ];
        $field = 'member_detail.*,a.real_name,a.user_name,a.password,a.id_card,a.referee_mobile,a.mobile,a.tel,a.user_status,a.type,a.region_id,a.node_id,a.create_time,a.delete_time,a.update_time,a.ip,a.last_login_ip,a.login_time';
        $member = $member->where('a.id', $id)->join($join)->alias('a')->field($field)->find();
        $this->assign("member", $member);
        $tplName = (!empty($member['type']) && $member['type']==1)?'personalAudit':'companyAudit';
        return $this->fetch($tplName);        
    }
    //审核功能
    public function auditPost()
    {
        if($this->request->isPost()){
            $post   = $this->request->param(); 
            //dump($post);exit;
            //身份证存储
            $rs=db::name('member_card')->where('mid',$post['mid'])->value('id');
			if(empty($rs)){
                $pic1=APP_PATH.'../public'.DS.'api'.DS.'id_card'.DS;
                $admin = Session::get('admin');
                $deposit_operator = empty($admin['name'])?'':$admin['name'];//操作人员
                $bank_pic=$this->get_base64_img($post['id_pic'],$pic1);
                $pic='/api/id_card/'.$bank_pic;
                $arr=[
                    'name'=>$post['id_name'],
                    'mid'=>$post['mid'],
                    'sex'=>$post['id_sex'],
                    'nation'=>$post['id_nation'],
                    'born'=>$post['id_born'],
                    'address'=>$post['id_address'],
                    'cardNo'=>$post['id_cardNo'],
                    'police'=>$post['id_police'],
                    'pic'=>$pic,
                    'deposit_operator'=>$deposit_operator,
                    'create_time'=>time()
                ];

                db::name('member_card')->insert($arr);
            }

            $member       = model('member');           
            //$resultMember = $member->isUpdate(true)->allowField($memberFields)->save($post);
            $resultMember = $member->where('id',$post['mid'])->setField('user_status', 1);
            \think\Log::record(json_encode($post).'审核的提交数据。');
            if($resultMember){
                $this->success("审核通过！", url("/Admin/Member/auditIndex"));
            }else{
                $this->success("审核失败！", url("/Admin/Member/auditIndex"));
            }
        }else{
            return json(['code'=>1,'msg'=>'数据未按post方法提交！']);
        
        }
        
    }

    public function forbid()
    {
        $this->success("操作成功！", url("/Admin/Member/auditIndex"));
    
    }
    //后台暂时不能增加会员
    public function add()
    {
        return $this->fetch();
    }
    //后台暂时不能增加会员
    public function addPost()
    {
        $post     = $_POST;
        $group_id             = $post['group_id'];
        $post['type']         = 2;
        unset($post['repass']);
        unset($post['group_id']);
        $admin             = model('admin');
        $id                = $admin->save($post);
        $LastId            = $admin->getLastInsID();
        $group['uid']      = $LastId;
        $group['group_id'] = $group_id;
        $result_group      = Db::name('auth_group_access')->insert($group);
        if($id&&$result_group){
            return json(['code'=>1,'msg'=>'管理员添加成功！']);
        }else if($result_group){
            return json(['code'=>1,'msg'=>'角色增加失败！需要重新设置该用户权限！']);
        }else{
            return json(['code'=>1,'msg'=>'增加失败！']);
        }
    } 
    
    public function update()
    {
        if($this->request->isPost()){
            $post   = $this->request->param();

            $member       = model('member');
            $memberDetail = model('MemberDetail');
            
            $memberFields = 'real_name,user_name,password,id_card,referee_mobile,mobile,tel,user_status,id_card,referee_mobile
                type,region_id,node_id';            
            $detailFields ='silver_card,gold_card,user_nickname,sex,email,account_name,bank_name,bank_card';
            
            
            if(!empty($post['vip_no'])){
				$vip  = Db::name('tb_vip_info')->where('isid', $post['mid'])->field('vip_no')->find();
				//不存在时 增加
				if(empty($vip)){
					$vip['vip_no'] = $post['vip_no'];
					$vip['vip_score_y'] = 0.0000;
					$vip['isid'] = $post['mid'];
					$vip['vip_type'] = 9;
					$vipResult = Db::name('tb_vip_info')->insert($vip);
				}else{
					$vipResult = Db::name('tb_vip_info')->where('isid',$post['mid'])
                            ->update(['vip_no'=> $post['vip_no']]);
					
				}
			}
			$post['silver_card'] = $post['vip_no'];
			$post['gold_card']   = $post['vip_no'];
            $resultDetail = $memberDetail->allowField($detailFields)->save($post,['id' => $post['id']]);            
            $resultMember = $member->allowField($memberFields)->save($post,['id' => $post['mid']]);
			
            if($resultMember&&$resultDetail){
                return json(['code'=>1,'msg'=>'会员更新成功！']);
            }else if($resultDetail){
                return json(['code'=>1,'msg'=>'会员更新失败！']);
            }else{
                return json(['code'=>1,'msg'=>'会员更新失败！']);
            }
        }else{
            return json(['code'=>1,'msg'=>'数据未按post方法提交！']);
            
        }       

    }
    public function auditUpdate()
    {
        if($this->request->isPost()){
            $post   = $this->request->param();
            //年月日转时间戳
            unset($post['create_time']);
            $member       = model('member');
            $memberDetail = model('MemberDetail');
    
            $memberFields = 'real_name,id_card,address';
            $detailFields ='account_name,bank_name,bank_card';
    
    
            //$resultDetail = $memberDetail->allowField($detailFields)->save($post,['mid' => $post['mid']]);
            $resultDetail = $memberDetail->where('mid',$post['mid'])
                            ->update(  ['bank_name'=>$post['bank_name'],'bank_card'=>$post['bank_card']]);
            $resultMember = $member->allowField($memberFields)->save($post,['id' => $post['mid']]);
    
        if($resultMember&&$resultDetail){
                $this->success("客户更新成功！", url("/Admin/Member/auditIndex")); 
            }else{
                $this->success("客户更新失败！", url("/Admin/Member/auditIndex"));
            }
        }else{
            $this->success("数据未post请求！", url("/Admin/Member/auditIndex"));
    
        }
    
    }
    public function edit($id)
    {
        $member = model('member');
        $join = [
            ['__MEMBER_DETAIL__ member_detail','a.id = member_detail.mid'],
        ];
        $field = 'member_detail.*,a.real_name,a.user_name,a.password,a.id_card,a.referee_mobile,a.mobile,a.tel,a.user_status,a.type,a.region_id,a.node_id,a.create_time,a.delete_time,a.update_time,a.ip,a.last_login_ip,a.login_time,a.more';
        $member = $member->where('a.id', $id)->join($join)->alias('a')->field($field)->find();
		$vipNo  = Db::name('tb_vip_info')->where('isid', $id)->field('vip_no,vip_score_y')->find();
		if(!empty($vipNo)){
			$member = array_merge($member->getData(),$vipNo);
		}else{
			$vipNo['vip_no'] = null;
			$vipNo['vip_score_y'] = '0.00';
			$member = array_merge($member->getData(),$vipNo);
		}
		
        $this->assign("member", $member);
        $tplName = (!empty($member['type']) && $member['type']==1)?'personal':'company';
		
        return $this->fetch($tplName);
    }
    public function del($id,$recover=false)
    {
        $action='';
        $admin = model('member');
        if($recover){
            $action ='恢复';
            $result = $admin->where('id', $id)->update(['delete_time' => 0]);
        }else{
            $result = $admin->where('id', $id)->update(['delete_time' => time()]);
            $action ='删除';
        }
        
        if($result){
            return json(['code'=>1,'msg'=>$action.'成功！']);
        }else {
            return json(['code'=>1,'msg'=>$action.'失败！']);
        }
        
    }
    public function delAll()
    {
        $admin = model('member');
        $ids = empty($_POST['ids']) ? '' : $_POST['ids'];
        if(empty($ids)){
            return json(['code'=>1,'msg'=>'参数错误！']);
        }else {
            
            $ids = implode(',', $ids);
            $where = "id in($ids)";
            $group_where = "uid in($ids)";
        }
        $admin_result = $admin->where($where)->update(['delete_time' => time()]);
        $group_result =Db::name('auth_group_access')->where($group_where)->update(['delete_time' => time()],['user_status' => 2]);
        if($admin_result&&$group_result){
            return json(['code'=>1,'msg'=>'删除成功！']);
        }else {
            return json(['code'=>1,'msg'=>'删除失败！']);
        }
    
    }
    //改变个人会员状态 
    public function changeState($id,$state)
    {
        $admin = model('member');
        $result = $admin->where('id', $id)->update(['user_status' => $state]);
        if($result){
            return json(['code'=>1,'msg'=>'状态设置成功！']);
        }else {
            return json(['code'=>1,'msg'=>'状态设置失败！']);
        }    
    }

    //修改手机号模板页
    public function phoneUpdate(){
        $param = $this->request->param();
        $memberService =new MemberService();
        $member = $memberService->phoneUpdate($param);
        $this->assign("member", $member);
        $this->assign("filter", $param);//设置过滤条件
        $this->setNav('修改手机号列表');
        //dump($member);exit;
        return $this->fetch();
    }

    //驳回手机中转页
    public function phoneExit(){
        $param = $this->request->param();

        $this->assign('id',$param['id']);
        return $this->fetch();
    }

    //修改手机号状态
    public function phonePass(){
        $param = $this->request->param();
        $phone=db::name('member_phone')->where('id',$param['id'])->find();
		if($phone['status']==1){
			if($param['type']==1){
				//通过
				db::name('member_phone')->where('id',$param['id'])->update(['status'=>2]);
				db::name('member')->where('referee_mobile',$phone['mobile'])->update(['referee_mobile'=>$phone['phone']]);
				$result=db::name('member')->where('id',$phone['mid'])->update(['mobile'=>$phone['phone'],'phone_status'=>2]);
				if($result){
					///通过则把当前所有用户所有未执行状态改为空过
				   $text='修改手机成功,原手机号'.substr_replace($phone['mobile'],'****',3,4).',现手机号'.substr_replace($phone['phone'],'****',3,4);
				   $text1='您的审核已通过';
				   $this->sendNotice($text,$text1,$phone['openid'],$phone['form_id']);
				   db::name('member_phone')->where('mid',$phone['mid'])->where('status',1)->update(['status'=>2]);
				   return json(['code'=>1,'msg'=>'手机号成功修改']);
				}else{
				   return json(['code'=>2,'msg'=>'修改失败，请重试！']);
				}
			}else{
				//驳回
				$rs=db::name('member_phone')->where('id',$param['id'])->update(['status'=>3,'commit'=>$param['commit']]);
				$result=db::name('member')->where('id',$phone['mid'])->update(['phone_status'=>3]);
				if($result&&$rs){
				   $text='驳回原因：'.$param['commit'];
				   $text1='您的审核已驳回';
				   $this->sendNotice($text,$text1,$phone['openid'],$phone['form_id']);
				   return json(['code'=>3,'msg'=>'手机号成功驳回']);
				}else{
				   return json(['code'=>4,'msg'=>'驳回失败，请重试！']);
				}
			}
		}else{
			return json(['code'=>5,'msg'=>'已提交，请刷新页面']);
		}
    }
    //推荐人状态
    public function recommend_status(){
        $param = $this->request->param();
        db::name('member_referee')->where('mid',$param['id'])->update(['status'=>'2']);
        Db::execute("update st_member set referee_moblie_status=2 where id=".$param['id']);
        return json(['code'=>1,'msg'=>'成功，请刷新页面']);
    }
    //推荐人申请
    public function recommend(){
        $param = $this->request->param();
        $memberService =new MemberService();
        $member = $memberService->recommend($param);
        $this->assign("member", $member);
        $this->assign("filter", $param);//设置过滤条件
        $this->setNav('推荐人申请列表');
        return $this->fetch();
    }

    //修改银行卡信息
    public function bankUpdate(){
        $param = $this->request->param();
        $memberService =new MemberService();
        $member = $memberService->bank($param);
        $this->assign("member", $member);
        $this->assign("filter", $param);//设置过滤条件
        $this->setNav('修改银行卡列表');
        return $this->fetch();
    }
    //驳回银行卡中转页
    public function bankExit(){
        $param = $this->request->param();

        $this->assign('id',$param['id']);
        return $this->fetch();
    }
    //修改银行卡状态
    public function bankPass(){
        $param = $this->request->param();
        $phone=db::name('member_bank')->where('id',$param['id'])->find();
		if($phone['status']==1){
			if($param['type']==1){
				//通过
				db::name('member_bank')->where('id',$param['id'])->update(['status'=>2]);
				db::name('member')->where('id',$phone['mid'])->update(['bank_status'=>2]);
				$data=[
					'account_name'=>$phone['name'],
					'bank_name'=>$phone['bank_name'],
					'bank_card'=>$phone['bank_card']
				];
				$result=db::name('member_detail')->where('mid',$phone['mid'])->update($data);
				if($result){
					///通过则把当前所有用户所有未执行状态改为空过
				   $text1='您的审核已通过';
				   $text='修改银行卡成功,现银行卡后四位'.substr($phone['bank_card'],-4);
				   $ra=$this->sendNotice($text,$text1,$phone['openid'],$phone['form_id']);
				   return json(['code'=>1,'msg'=>$ra]);
				}else{
				   return json(['code'=>2,'msg'=>'修改失败，请重试！']);
				}
			}else{
				//驳回
				$rs=db::name('member_bank')->where('id',$param['id'])->update(['status'=>3,'commit'=>$param['commit']]);
				$result=db::name('member')->where('id',$phone['mid'])->update(['bank_status'=>3]);
				if($result&&$rs){
				   $text='驳回原因：'.$param['commit'];
				   $text1='您的审核已驳回';
				   $this->sendNotice($text,$text1,$phone['openid'],$phone['form_id']);
				   return json(['code'=>3,'msg'=>'银行卡成功驳回']);
				}else{
				   return json(['code'=>4,'msg'=>'驳回失败，请重试！']);
				}      
			}
		}else{
			return json(['code'=>5,'msg'=>'已提交，请刷新页面']);
		}
    }
       //推送成功后的小程序消息
    public function sendNotice($type,$type1,$openid,$formId){
        Loader::import('wxbiz.WXBiz');
        $accessToken = Cache::get('accessToken');
        if(!$accessToken){
            $wxbiz = new \WXBiz();
            $accessToken = $wxbiz->accessToken();
            if($accessToken){
                Cache::set('accessToken',$accessToken,7200);
            }else{
                return false;
            }
        }
        // dump($accessToken);exit;

        $dataArray   =array('keyword1'=>['value'=>$type1],'keyword2'=>['value'=>$type],
            'keyword3'=>['value'=>date('Y-m-d H:i:s')]);
        $post_data=array('data'=>$dataArray,'template_id'=>'U3sneg96DS4dQ4x33SisI3fkXme5BT0DY5tYPyVH2m8',
                          'form_id'=>$formId,'touser'=>$openid);
        $wxbiz  = new \WXBiz();
        $result    = $wxbiz->sendNotice($accessToken,json_encode($post_data));
        if($result['errcode']===0){
            return '发送成功！';
        }else{
            return $result;
        }
    }
	/**
* base64转码图片
* @param $base64
* @param string $path
* @return bool|string
*/
	function get_base64_img($base64,$path){
		if (preg_match('/^(data:\s*image\/(\w+);base64,)/', $base64, $result)){
			if($result[2] == 'jpeg'){
				$image_name = uniqid().'.jpg';
				//纯粹是看jpeg不爽才替换的
			}else{
				$image_name = uniqid().'.'.$result[2];
			}
			$new_file = $path.time()."{$image_name}";
			if (file_put_contents($new_file, base64_decode(str_replace($result[1], '', $base64)))){
			return time().$image_name;
			}else{
			return  false;
			}
		}
	}
}
